package handler

import (
	"cucfms/cache"
	"cucfms/models"
	"cucfms/pkg"
	"github.com/gin-gonic/gin"
)

func Logan(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"mag":  "字段不可为空",
		})
		return
	}
	redis_key := "logan_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount > 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"mag":  "密码错误3次，禁止登录",
		})
		return
	}
	var news models.User

	err := models.DB.Where("username =?", username).First(&news).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"mag":  "服务和密码错误",
		})
		return
	}
	if news.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"mag":  "服务不存在",
		})
		return
	}
	if news.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			c.JSON(200, gin.H{
				"code": 500,
				"mag":  "密码错误3次，封禁2个小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"mag":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"mag":  "登录成功",
	})
	return
}
